package com.znufe.exam.controller.admin;


//import com.alibaba.excel.EasyExcelFactory;
//import com.alibaba.excel.ExcelWriter;
//import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;
import com.znufe.exam.configuration.config.model.LoginUser;
import com.znufe.exam.configuration.config.service.TokenService;
import com.znufe.exam.configuration.config.utils.ServletUtils;
import com.znufe.exam.domain.Student;
import com.znufe.exam.domain.User;
import com.znufe.exam.service.ExamGradeService;
import com.znufe.exam.service.QuestionService;
import com.znufe.exam.service.StudentService;
import com.znufe.exam.service.excel.TrueFalseService;
import com.znufe.exam.service.excel.ExcelService;
import com.znufe.exam.service.excel.MultipleChoiceService;
import com.znufe.exam.service.excel.ShortAnswerService;
import com.znufe.exam.service.excel.SingleChoiceService;
import com.znufe.exam.utility.easyexcel.EasyExcelListener;
import com.znufe.exam.utility.easyexcel.EasyExcelUtils;
import com.znufe.exam.utility.easyexcel.ExcelCheckErrDto;
import com.znufe.exam.utility.excel.EasyExcelUtil;
import com.znufe.exam.utility.excel.SpinnerWriteHandler;
import com.znufe.exam.viewmodel.admin.grade.StudentIndividualGradeRequestVM;
import com.znufe.exam.viewmodel.admin.grade.StudentIndividualGradeResponseVM;
import com.znufe.exam.viewmodel.admin.grade.StudentIndividualGradeToExcelVM;
import com.znufe.exam.viewmodel.admin.question.QuestionEditItemVM;
import com.znufe.exam.viewmodel.admin.question.QuestionEditRequestVM;
import com.znufe.exam.viewmodel.admin.question.excelmodel.*;
import com.znufe.exam.viewmodel.admin.student.ErrorFromStudentExcel;
import com.znufe.exam.viewmodel.admin.student.StudentFromExcelVM;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
//import com.alibaba.excel.EasyExcel;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(description = "导入与导出（Excel）",value="导入与导出（Excel）" )
@RestController("AdminExcelController")
@RequestMapping(value = "/api/admin/excel")
@AllArgsConstructor
public class ExcelController extends BaseApiController {

    @Autowired
    private ExcelService excelService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private ExamGradeService examGradeService;
    @Autowired
    private SingleChoiceService singleChoiceService;
    @Autowired
    private MultipleChoiceService multipleChoiceService;
    @Autowired
    private TrueFalseService trueFalseService;
    @Autowired
    private ShortAnswerService shortAnswerService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private TokenService tokenService;

    @RequestMapping(value = "/export_student_template" , method = RequestMethod.POST)
    //,produces = "application/json;charset=UTF-8"
    @ApiOperation(value = "学生批量导入的模板下载接口",
            notes = "下载学生批量导入的模板，作者：lin keqing")
    public void exportStudentTemplate(HttpServletResponse response) {
        String FILE_NAME = "学生导入模板";
        String STUDENT_INFO = "学生信息";

        List<StudentFromExcelVM> studentList = new ArrayList<>();
        /*
        for (int i = 0; i < 5; ++i) {
            ExcelToStudent stu = new ExcelToStudent();
            stu.setStuName("张胜男" + i);
            stu.setGender("男");
            stu.setStuPhone("1388474954" + i);
            stu.setVoteId("" + i);
            studentList.add(stu);
            System.out.println(stu);
        }*/
        try {
            EasyExcelUtil.writeExcel(response, studentList, FILE_NAME, STUDENT_INFO,
                    new StudentFromExcelVM(), ExcelTypeEnum.XLSX);
            return;
            //return RestResponse.ok("导出到Excel成功");
        } catch (Exception e) {
            e.printStackTrace();
            return;
            //return RestResponse.fail(421,"excel读取失败，请重试");
        }

    }

    @RequestMapping(value = "/import_excel_for_student/{classId}" , method = RequestMethod.POST)
    @ApiOperation(value = "批量导入学生的接口",
            notes = "传入班级id, 进行数据校验，校验合法后导入学生，作者：lin keqing")
    public RestResponse<List<StudentFromExcelVM>> ImportStudent(HttpServletResponse response,
                               MultipartFile uploadExcel,
                              @PathVariable Integer classId) throws IOException {
        /*
        if (uploadExcel.isEmpty()) {
            return RestResponse.fail(SystemCode.FileEmptyError.getCode(),SystemCode.FileEmptyError.getMessage());
        }
        String fileName = uploadExcel.getOriginalFilename();
        System.out.println("fileName: " + fileName);
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        if (!("xls".equals(suffix) || "xlsx".equals(suffix))) {
            return RestResponse.fail(SystemCode.FileFormatError.getCode(),SystemCode.FileFormatError.getMessage());
        }
        */
        SystemCode checkCode = EasyExcelUtil.checkFile(uploadExcel);
        if (checkCode != SystemCode.OK) {
            return RestResponse.fail(checkCode.getCode(),checkCode.getMessage());
        }

        EasyExcelListener easyExcelListener = new EasyExcelListener(excelService, classId, StudentFromExcelVM.class);
        EasyExcelFactory.read(uploadExcel.getInputStream(), StudentFromExcelVM.class, easyExcelListener)
                .sheet().doRead();
        List<ExcelCheckErrDto<StudentFromExcelVM>> errList = easyExcelListener.getErrList();
        // 如果包含错误信息就导出错误信息
        if (!errList.isEmpty()) {
            System.out.println("数据不正确，我在controller.ImportStudent里 我进来了，快看看！");
            List<ErrorFromStudentExcel> excelErrDtos = errList.stream().map(excelCheckErrDto -> {
                ErrorFromStudentExcel userExcelErrDto = JSON.parseObject(
                        JSON.toJSONString(excelCheckErrDto.getT()),
                        ErrorFromStudentExcel.class);
                userExcelErrDto.setErrMsg(excelCheckErrDto.getErrMsg());
                return userExcelErrDto;
            }).collect(Collectors.toList());
            EasyExcelUtils.webWriteExcel(response, excelErrDtos, ErrorFromStudentExcel.class,
                    "用户导入错误信息");
            return new RestResponse<>(2, "输入的数据有错误，请下载错误信息提示文件！");
        }
        List<StudentFromExcelVM> sucList = easyExcelListener.getSuccessList();
        for (StudentFromExcelVM sucStudent : sucList) {
            System.out.println("我在controller里：" + sucStudent);
        }
        List<Student> toImportList = sucList.stream().map(s -> {
            Student student = new Student();
            student.setStuName(s.getStuName());
            student.setStuPhone(s.getStuPhone());
            student.setVoteBaseId(s.getVoteBaseId());
            student.setNote("使用批量导入新增的学生");
            student.setClassId(classId);
            Integer sex = "男".equals(s.getGender()) ? 1 : 0;
            student.setGender(sex);
            student.setVoteId(Integer.parseInt(s.getVoteId()));
            return student;
        }).collect(Collectors.toList());
        studentService.insertBatchStudent(toImportList);
        return RestResponse.ok(sucList);

        /**
         // 成功的测试
        try {
            List<StudentFromExcelVM> studentList = EasyExcelUtil.readExcelWithModel(
                    uploadExcel.getInputStream(),
                    StudentFromExcelVM.class,
                    ExcelTypeEnum.XLSX);
            for (StudentFromExcelVM student : studentList) {
                System.out.println(student);
            }
            return RestResponse.ok("解析学生信息Excel成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(421,"excel读取失败，请重试");
        }
         **/

    }


    @RequestMapping(value = "/export_student_individual_grade" , method = RequestMethod.POST)
    @ApiOperation(value = "导出某个学生成绩的接口",
            notes = "查出某个学生的成绩，导出成excel，作者：lin keqing")
    public void exportStudentIndividualGrade(@RequestBody StudentIndividualGradeRequestVM model,
                                             HttpServletResponse response) throws IOException {
        model = StudentIndividualGradeRequestVM.wipeBlank(model);
        List<StudentIndividualGradeResponseVM> studentGradeList = examGradeService
                .getStudentIndividualGradeInfo(model);
        List<StudentIndividualGradeToExcelVM> toExcelList = studentGradeList.stream()
                .map(g -> {
                    StudentIndividualGradeToExcelVM toExcel = modelMapper
                            .map(g, StudentIndividualGradeToExcelVM.class);
                    return toExcel;
                }).collect(Collectors.toList());
        EasyExcelUtils.webWriteExcel(response, toExcelList,  
                StudentIndividualGradeToExcelVM.class, model.getStuName() + "同学成绩单");
        return;
    }


    @RequestMapping(value = "/export_question_template" , method = RequestMethod.POST)
    @ApiOperation(value = "试题批量导入的模板下载接口",
            notes = "将单选题、多选题、判断题、简答题的模板导出到一个excel中，每个题型对应一个sheet，" +
                    "作者：lin keqing")
    public void exportQuestionTemplate(HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = EasyExcelUtils.getFileOutPutStream(response,"试题导入模板");
        HorizontalCellStyleStrategy fileStrategy = EasyExcelUtils.fileHeadStrategy();

        List<SingleChoiceFromExcelVM> singleChoiceVMList = new ArrayList<>();
        List<MultipleChoiceFromExcelVM> multipleChoiceVMList = new ArrayList<>();
        List<TrueFalseFromExcelVM> trueFalseVMList = new ArrayList<>();
        List<ShortAnswerFromExcelVM> shortAnswerVMList = new ArrayList<>();

        ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
        WriteSheet writeSheet;
        String[] hardNess = {"1", "2", "3", "4", "5"};

        // 构建单选题模板sheet
        String[] choiceArray = {"A", "B", "C", "D", "E", "F"};
        Map<Integer,String[]> singleChoiceMap = new HashMap<>();
        singleChoiceMap.put(7, choiceArray);
        singleChoiceMap.put(10, hardNess);
        writeSheet = EasyExcel.writerSheet(0,"单选题")
                .head(SingleChoiceFromExcelVM.class)
                .registerWriteHandler(fileStrategy)
                .registerWriteHandler(new SpinnerWriteHandler(singleChoiceMap))
                .build();
        excelWriter.write(singleChoiceVMList, writeSheet);
        // 构建多选题模板sheet
        String[] answerA = {"A"};
        String[] answerB = {"B"};
        String[] answerC = {"C"};
        String[] answerD = {"D"};
        String[] answerE = {"E"};
        String[] answerF = {"F"};
        Map<Integer,String[]> multipleChoiceMap = new HashMap<>();
        multipleChoiceMap.put(7, answerA);
        multipleChoiceMap.put(8, answerB);
        multipleChoiceMap.put(9, answerC);
        multipleChoiceMap.put(10, answerD);
        multipleChoiceMap.put(11, answerE);
        multipleChoiceMap.put(12, answerF);
        multipleChoiceMap.put(15, hardNess);
        writeSheet = EasyExcel.writerSheet(1,"多选题")
                .head(MultipleChoiceFromExcelVM.class)
                .registerWriteHandler(fileStrategy)
                .registerWriteHandler(new SpinnerWriteHandler(multipleChoiceMap))
                .build();
        excelWriter.write(multipleChoiceVMList, writeSheet);
        // 构建判断题模板sheet
        String[] answerArray = {"对", "错"};
        Map<Integer,String[]> trueFalseMap = new HashMap<>();
        trueFalseMap.put(1, answerArray);
        trueFalseMap.put(4, hardNess);
        writeSheet = EasyExcel.writerSheet(2, "判断题")
                .head(TrueFalseFromExcelVM.class)
                .registerWriteHandler(fileStrategy)
                .registerWriteHandler(new SpinnerWriteHandler(trueFalseMap))
                .build();
        excelWriter.write(trueFalseVMList, writeSheet);
        // 构建简答题模板sheet
        Map<Integer, String[]> shortAnswerMap = new HashMap<>();
        shortAnswerMap.put(4, hardNess);
        writeSheet = EasyExcel.writerSheet(3,"简答题")
                .head(ShortAnswerFromExcelVM.class)
                .registerWriteHandler(fileStrategy)
                .registerWriteHandler(new SpinnerWriteHandler(shortAnswerMap))
                .build();
        excelWriter.write(shortAnswerVMList, writeSheet);

        excelWriter.finish();
        return;
    }


    @RequestMapping(value = "/import_excel_for_question" , method = RequestMethod.POST)
    @ApiOperation(value = "批量导入试题的接口",
            notes = "传入试题模板 进行数据校验，校验合法后导入试题，作者：lin keqing")
    public RestResponse<List<QuestionEditRequestVM>> importQuestion(HttpServletResponse response,
                                                                    MultipartFile uploadExcel) throws IOException {
        SystemCode checkCode = EasyExcelUtil.checkFile(uploadExcel);
        if (checkCode != SystemCode.OK) {
            return RestResponse.fail(checkCode.getCode(),checkCode.getMessage());
        }

        ExcelReader excelReader = EasyExcel.read(uploadExcel.getInputStream()).build();
        // 针对每个sheet构造一个readSheet对象
        EasyExcelListener singleChoiceListener = new EasyExcelListener(singleChoiceService,
                1, SingleChoiceFromExcelVM.class);
        ReadSheet singleChoiceRS = EasyExcel.readSheet(0)
                .head(SingleChoiceFromExcelVM.class)
                .registerReadListener(singleChoiceListener)
                .build();

        EasyExcelListener multipleChoiceListener = new EasyExcelListener(multipleChoiceService,
                2, MultipleChoiceFromExcelVM.class);
        ReadSheet multipleChoiceRS = EasyExcel.readSheet(1)
                .head(MultipleChoiceFromExcelVM.class)
                .registerReadListener(multipleChoiceListener)
                .build();

        EasyExcelListener trueFalseListener = new EasyExcelListener(trueFalseService,
                3, TrueFalseFromExcelVM.class);
        ReadSheet trueFalseRS = EasyExcel.readSheet(2)
                .head(TrueFalseFromExcelVM.class)
                .registerReadListener(trueFalseListener)
                .build();

        EasyExcelListener shortAnswerListener = new EasyExcelListener(shortAnswerService,
                5, ShortAnswerFromExcelVM.class);
        ReadSheet shortAnswerRS = EasyExcel.readSheet(3)
                .head(ShortAnswerFromExcelVM.class)
                .registerReadListener(shortAnswerListener)
                .build();

        excelReader.read(singleChoiceRS, multipleChoiceRS, trueFalseRS, shortAnswerRS);
        excelReader.finish();

        List<ExcelCheckErrDto<SingleChoiceFromExcelVM>> singleChoiceErrList =
                singleChoiceListener.getErrList();
        List<ExcelCheckErrDto<MultipleChoiceFromExcelVM>> multipleChoiceErrList =
                multipleChoiceListener.getErrList();
        List<ExcelCheckErrDto<TrueFalseFromExcelVM>> trueFalseErrList =
                trueFalseListener.getErrList();
        List<ExcelCheckErrDto<ShortAnswerFromExcelVM>> shortAnswerErrList =
                shortAnswerListener.getErrList();

        if (!singleChoiceErrList.isEmpty() || !multipleChoiceErrList.isEmpty() ||
                !trueFalseErrList.isEmpty() || !shortAnswerErrList.isEmpty()) {
            // 导出文件的 输出流、表头策略准备
            ServletOutputStream outputStream = EasyExcelUtils.getFileOutPutStream(response,"试题导入数据错误信息");
            HorizontalCellStyleStrategy fileStrategy = EasyExcelUtils.fileHeadStrategy();
            // 为导出文件中的sheet准备 writeSheet，excelWriter相关工具类
            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
            WriteSheet writeSheet;

            // 如果singleChoice有错误， 拿出singleChoice中的错误信息
            String scSheetName = singleChoiceErrList.isEmpty() ? "单选题数据无错误" : "单选题错误数据信息";
            List<ErrorFromSingleChoiceExcel> singleChoiceErrDtos = getSingleChoiceErr(singleChoiceErrList);
            writeSheet = EasyExcel.writerSheet(0, scSheetName)
                    .head(ErrorFromSingleChoiceExcel.class)
                    .registerWriteHandler(fileStrategy)
                    .build();
            excelWriter.write(singleChoiceErrDtos, writeSheet);

            // 如果multipleChoice有错误， 拿出multipleChoice中的错误信息
            String mcSheetName = multipleChoiceErrList.isEmpty() ? "多选题数据无错误" : "多选题错误数据信息";
            List<ErrorFromMultipleChoiceExcel> multipleChoiceErrDtos = getMultipleChoiceErr(multipleChoiceErrList);
            writeSheet = EasyExcel.writerSheet(1, mcSheetName)
                    .head(ErrorFromMultipleChoiceExcel.class)
                    .registerWriteHandler(fileStrategy)
                    .build();
            excelWriter.write(multipleChoiceErrDtos, writeSheet);

            // 如果trueFalse有错误， 拿出trueFalse中的错误信息
            String tfSheetName = trueFalseErrList.isEmpty() ? "判断题数据无错误" : "判断题错误数据信息";
            List<ErrorFromTrueFalseExcel> trueFalseErrDtos = getTrueFalseErr(trueFalseErrList);
            writeSheet = EasyExcel.writerSheet(2, tfSheetName)
                    .head(ErrorFromTrueFalseExcel.class)
                    .registerWriteHandler(fileStrategy)
                    .build();
            excelWriter.write(trueFalseErrDtos, writeSheet);

            // 如果shortAnswer有错误， 拿出shortAnswer中的错误信息
            String saSheetName = shortAnswerErrList.isEmpty() ? "简答题数据无错误" : "简答题错误数据信息";
            List<ErrorFromShortAnswerExcel> shortAnswerErrDtos = getShortAnswerErr(shortAnswerErrList);
            writeSheet = EasyExcel.writerSheet(3,saSheetName)
                    .head(ErrorFromShortAnswerExcel.class)
                    .registerWriteHandler(fileStrategy)
                    .build();
            excelWriter.write(shortAnswerErrDtos, writeSheet);

            excelWriter.finish();
            return new RestResponse<>(2, "输入的数据有错误，请下载错误信息提示文件！");
        }

        // 这个List作为准备插入到数据库中的所有试题的集合
        List<QuestionEditRequestVM> allQuestionToImportList = new ArrayList<>();

        // 将单选题ExcelVM转化为QuestionEditRequestVM
        List<SingleChoiceFromExcelVM> singleChoiceSucList = singleChoiceListener.getSuccessList();
        List<QuestionEditRequestVM> singleChoiceQuestion = singleChoiceExcelToQueEditVM(singleChoiceSucList);
        allQuestionToImportList.addAll(singleChoiceQuestion);

        // 将多选题ExcelVM转化为QuestionEditRequestVM
        List<MultipleChoiceFromExcelVM> multipleChoiceSucList = multipleChoiceListener.getSuccessList();
        List<QuestionEditRequestVM> multipleChoiceQuestion = multipleChoiceExcelToQueEditVM(multipleChoiceSucList);
        allQuestionToImportList.addAll(multipleChoiceQuestion);

        // 将判断题ExcelVM转化为QuestionEditRequestVM
        List<TrueFalseFromExcelVM> trueFalseSucList = trueFalseListener.getSuccessList();
        List<QuestionEditRequestVM> trueFalseQuestion = trueFalseExcelToQueEditVM(trueFalseSucList);
        allQuestionToImportList.addAll(trueFalseQuestion);

        // 将简答题ExcelVM转化为QuestionEditRequestVM
        List<ShortAnswerFromExcelVM> shortAnswerSucList = shortAnswerListener.getSuccessList();
        List<QuestionEditRequestVM> shortAnswerQuestion = shortAnswerExcelToQueEditVM(shortAnswerSucList);
        allQuestionToImportList.addAll(shortAnswerQuestion);

        //当前用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        User user = loginUser.getUser();

        for (QuestionEditRequestVM vm : allQuestionToImportList) {
            System.out.println("我在ExcelController的ImportQuestion里" + vm);
        }
        for(QuestionEditRequestVM vm : allQuestionToImportList) {
            questionService.insertFullQuestion(vm, user.getId());
        }
        return RestResponse.ok(allQuestionToImportList);
    }

     /** 下面四个方法： 在用户输入数据不合法时， 各种题型对应拿出自己的错误提示信息 **/

    // 拿出单选题的错误信息
    private List<ErrorFromSingleChoiceExcel> getSingleChoiceErr(List<ExcelCheckErrDto<SingleChoiceFromExcelVM>> singleChoiceErrList) {
        List<ErrorFromSingleChoiceExcel> singleChoiceErrDtos = singleChoiceErrList.stream().map(excelCheckErrDto -> {
            ErrorFromSingleChoiceExcel singleChoiceErrDto = JSON.parseObject(
                    JSON.toJSONString(excelCheckErrDto.getT()),
                    ErrorFromSingleChoiceExcel.class);
            singleChoiceErrDto.setErrMsg(excelCheckErrDto.getErrMsg());
            return singleChoiceErrDto;
        }).collect(Collectors.toList());
        return singleChoiceErrDtos;
    }


    // 拿出多选题的错误信息
    private List<ErrorFromMultipleChoiceExcel> getMultipleChoiceErr(List<ExcelCheckErrDto<MultipleChoiceFromExcelVM>> multipleChoiceErrList) {
        List<ErrorFromMultipleChoiceExcel> multipleChoiceErrDtos = multipleChoiceErrList.stream().map(excelCheckErrDto -> {
            ErrorFromMultipleChoiceExcel multipleChoiceErrDto = JSON.parseObject(
                    JSON.toJSONString(excelCheckErrDto.getT()),
                    ErrorFromMultipleChoiceExcel.class);
            multipleChoiceErrDto.setErrMsg(excelCheckErrDto.getErrMsg());
            return multipleChoiceErrDto;
        }).collect(Collectors.toList());
        return multipleChoiceErrDtos;
    }


    // 拿出判断题的错误信息
    private List<ErrorFromTrueFalseExcel> getTrueFalseErr(List<ExcelCheckErrDto<TrueFalseFromExcelVM>> trueFalseErrList) {
        List<ErrorFromTrueFalseExcel> trueFalseErrDtos = trueFalseErrList.stream().map(excelCheckErrDto -> {
            ErrorFromTrueFalseExcel trueFalseErrDto = JSON.parseObject(
                    JSON.toJSONString(excelCheckErrDto.getT()),
                    ErrorFromTrueFalseExcel.class);
            trueFalseErrDto.setErrMsg(excelCheckErrDto.getErrMsg());
            return trueFalseErrDto;
        }).collect(Collectors.toList());
        return trueFalseErrDtos;
    }


    // 拿出简答题的错误信息
    List<ErrorFromShortAnswerExcel> getShortAnswerErr(List<ExcelCheckErrDto<ShortAnswerFromExcelVM>> shortAnswerErrList) {
        List<ErrorFromShortAnswerExcel> shortAnswerErrDtos = shortAnswerErrList.stream().map(excelCheckErrDto -> {
            ErrorFromShortAnswerExcel shortAnswerErrDto = JSON.parseObject(
                    JSON.toJSONString(excelCheckErrDto.getT()),
                    ErrorFromShortAnswerExcel.class);
            shortAnswerErrDto.setErrMsg(excelCheckErrDto.getErrMsg());
            return shortAnswerErrDto;
        }).collect(Collectors.toList());
        return shortAnswerErrDtos;
    }

    /** 下面四个方法： 在用户输入数据合法后， 各种题型对应的ExcelVM转换为QuestionEditRequestVM **/

    // 将单选题ExcelVM 转化为 QuestionEditRequestVM
    private List<QuestionEditRequestVM> singleChoiceExcelToQueEditVM(List<SingleChoiceFromExcelVM> singleChoiceSucList) {
        List<QuestionEditRequestVM> singleChoiceQuestionList = singleChoiceSucList.stream().map(s -> {
            QuestionEditRequestVM singleChoiceQuestion = modelMapper.map(s, QuestionEditRequestVM.class);
            // 选项内容的转换
            List<QuestionEditItemVM> items = new ArrayList<>();
            if (s.getOptionA() != null) {
               QuestionEditItemVM itemA = new QuestionEditItemVM("A",
                       s.getOptionA(), s.getScore());
               items.add(itemA);
            }
            if (s.getOptionB() != null) {
                QuestionEditItemVM itemB = new QuestionEditItemVM("B",
                        s.getOptionB(), s.getScore());
                items.add(itemB);
            }
            if (s.getOptionC() != null) {
                QuestionEditItemVM itemC = new QuestionEditItemVM("C",
                        s.getOptionC(), s.getScore());
                items.add(itemC);
            }
            if (s.getOptionD() != null) {
                QuestionEditItemVM itemD = new QuestionEditItemVM("D",
                        s.getOptionD(), s.getScore());
                items.add(itemD);
            }
            if (s.getOptionE() != null) {
                QuestionEditItemVM itemE = new QuestionEditItemVM("E",
                        s.getOptionE(), s.getScore());
                items.add(itemE);
            }
            if (s.getOptionF() != null) {
                QuestionEditItemVM itemF = new QuestionEditItemVM("F",
                        s.getOptionF(), s.getScore());
                items.add(itemF);
            }
            singleChoiceQuestion.setItems(items);
            // 答案数组的转换
            List<String> correctArray = new ArrayList<>();
            correctArray.add(s.getCorrect());
            singleChoiceQuestion.setCorrectArray(correctArray);

            singleChoiceQuestion.setQuestionType(1);
            Integer difficult = s.getDifficultVM() == null ?
                                null : Integer.parseInt(s.getDifficultVM());
            singleChoiceQuestion.setDifficult(difficult);
            return singleChoiceQuestion;
        }).collect(Collectors.toList());
        return singleChoiceQuestionList;
    }

    // 将多选题ExcelVM 转化为 QuestionEditRequestVM
    List<QuestionEditRequestVM> multipleChoiceExcelToQueEditVM(List<MultipleChoiceFromExcelVM> multipleChoiceSucList) {
        List<QuestionEditRequestVM> multipleChoiceQuestionList = multipleChoiceSucList.stream().map(m -> {
            QuestionEditRequestVM multipleChoiceQuestion = modelMapper.map(m, QuestionEditRequestVM.class);
            // 选项内容的转换
            List<QuestionEditItemVM> items = new ArrayList<>();
            if (m.getOptionA() != null) {
                QuestionEditItemVM itemA = new QuestionEditItemVM("A",
                        m.getOptionA(), m.getScore());
                items.add(itemA);
            }
            if (m.getOptionB() != null) {
                QuestionEditItemVM itemB = new QuestionEditItemVM("B",
                        m.getOptionB(), m.getScore());
                items.add(itemB);
            }
            if (m.getOptionC() != null) {
                QuestionEditItemVM itemC = new QuestionEditItemVM("C",
                        m.getOptionC(), m.getScore());
                items.add(itemC);
            }
            if (m.getOptionD() != null) {
                QuestionEditItemVM itemD = new QuestionEditItemVM("D",
                        m.getOptionD(), m.getScore());
                items.add(itemD);
            }
            if (m.getOptionE() != null) {
                QuestionEditItemVM itemE = new QuestionEditItemVM("E",
                        m.getOptionE(), m.getScore());
                items.add(itemE);
            }
            if (m.getOptionF() != null) {
                QuestionEditItemVM itemF = new QuestionEditItemVM("F",
                        m.getOptionF(), m.getScore());
                items.add(itemF);
            }
            multipleChoiceQuestion.setItems(items);

            // 答案数组的转换
            List<String> correctArray = new ArrayList<>();
            if ("A".equals(m.getChooseA())) {
                correctArray.add(m.getChooseA());
            }
            if ("B".equals(m.getChooseB())) {
                correctArray.add(m.getChooseB());
            }
            if ("C".equals(m.getChooseC())) {
                correctArray.add(m.getChooseC());
            }
            if ("D".equals(m.getChooseD())) {
                correctArray.add(m.getChooseD());
            }
            if ("E".equals(m.getChooseE())) {
                correctArray.add(m.getChooseE());
            }
            if ("F".equals(m.getChooseF())) {
                correctArray.add(m.getChooseF());
            }
            multipleChoiceQuestion.setCorrectArray(correctArray);

            multipleChoiceQuestion.setQuestionType(2);
            Integer difficult = m.getDifficultVM() == null ?
                    null : Integer.parseInt(m.getDifficultVM());
            multipleChoiceQuestion.setDifficult(difficult);
            return multipleChoiceQuestion;
        }).collect(Collectors.toList());
        return multipleChoiceQuestionList;
    }

    // 将判断题ExcelVM 转化为 QuestionEditRequestVM
    List<QuestionEditRequestVM> trueFalseExcelToQueEditVM(List<TrueFalseFromExcelVM> trueFalseSucList) {
        List<QuestionEditRequestVM> trueFalseQuestionList = trueFalseSucList.stream().map(t -> {
            QuestionEditRequestVM trueFalseQuestion = modelMapper.map(t, QuestionEditRequestVM.class);
            // 选项内容的转换
            List<QuestionEditItemVM> items = new ArrayList<>();
            QuestionEditItemVM itemTrue = new QuestionEditItemVM("A","对", t.getScore());
            items.add(itemTrue);
            QuestionEditItemVM itemFalse = new QuestionEditItemVM("B", "错", t.getScore());
            items.add(itemFalse);
            trueFalseQuestion.setItems(items);

            // 设置正确答案
            String correct = "对".equals(t.getCorrectVM()) ? "A" : "B";
            trueFalseQuestion.setCorrect(correct);

            trueFalseQuestion.setQuestionType(3);
            Integer difficult = t.getDifficultVM() == null ?
                    null : Integer.parseInt(t.getDifficultVM());
            trueFalseQuestion.setDifficult(difficult);
            return trueFalseQuestion;
        }).collect(Collectors.toList());
        return trueFalseQuestionList;
    }

    // 将简答题ExcelVM 转化为 QuestionEditRequestVM
    List<QuestionEditRequestVM> shortAnswerExcelToQueEditVM(List<ShortAnswerFromExcelVM> shortAnswerSucList) {
        List<QuestionEditRequestVM> shortAnswerQuestionList = shortAnswerSucList.stream().map(a -> {
            QuestionEditRequestVM shortAnswerQuestion = modelMapper.map(a, QuestionEditRequestVM.class);
            List<QuestionEditItemVM> items = new ArrayList<>();
            shortAnswerQuestion.setItems(items);
            shortAnswerQuestion.setQuestionType(5);
            Integer difficult = a.getDifficultVM() == null ?
                    null : Integer.parseInt(a.getDifficultVM());
            shortAnswerQuestion.setDifficult(difficult);
            return shortAnswerQuestion;
        }).collect(Collectors.toList());
        return shortAnswerQuestionList;
    }


    /**
    @RequestMapping(value = "/uploadStudentExcel" , method = RequestMethod.POST)
    public RestResponse readExcel(MultipartFile uploadExcel) {
        if (uploadExcel.isEmpty()) {
            return RestResponse.fail(SystemCode.FileEmptyError.getCode(),SystemCode.FileEmptyError.getMessage());
        }
        String fileName = uploadExcel.getOriginalFilename();

        System.out.println("fileName: " + fileName);

        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        if (!("xls".equals(suffix) || "xlsx".equals(suffix))) {
            return RestResponse.fail(SystemCode.FileFormatError.getCode(),SystemCode.FileFormatError.getMessage());
        }
        try {
            InputStream inputStream = uploadExcel.getInputStream();
            List<List<Object>> list = ExcelUtil.readExcelFile(inputStream,fileName);
            inputStream.close();

            for (int i = 0; i < list.size(); i++) {
                List<Object> studentList = list.get(i);

                Student student = new Student();
                student.setStuName(studentList.get(0).toString());
                if (studentList.get(1).toString().equals("男")) {
                    student.setGender(1);
                } else if (studentList.get(1).toString().equals("女")) {
                    student.setGender(0);
                } else {
                    return RestResponse.fail(SystemCode.FileFormatError.getCode(), SystemCode.FileFormatError.getMessage());
                }
                student.setStuPhone(studentList.get(2).toString());
                student.setVoteId(Integer.parseInt(studentList.get(3).toString()));
                student.setCreateTime(new Date());
                System.out.println(student);
            }
            return RestResponse.ok("测试");
        } catch (Exception e) {
            return RestResponse.fail(421,"读取Excel文件失败");
        }
    }
    **/


    /**
    @RequestMapping(value = "downloadStudentExcel",method = RequestMethod.GET)
    public RestResponse downloadStudentExcel(HttpServletResponse response) throws UnsupportedEncodingException{
        System.out.println("11111111111111111111111111");
        String fileName = "";
        String filePath = "http://47.99.53.136:8001/static/upload/video/";
        File file = new File("D:\\资料\\曼城.JPG");
        System.out.println(file);
        if(file.exists()){
            System.out.println("333333333333333333333333333333333333");
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));
            byte[] buffer = new byte[1024];
            //文件输入流
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            //输出流
            OutputStream os = null;
            try {
                System.out.println("2222222222222222222222222222");
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer,0,1);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return RestResponse.fail(222,"下载失败");
    }

    @RequestMapping(value = "downloadPOI",method = RequestMethod.GET)
    public RestResponse downloadStudentExcel(HttpServletResponse response) throws UnsupportedEncodingException{
        HSSFWorkbook workbook =new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        int rowNum =0;
        //自定义列标题
        String[] headers ={"姓名","性别","职位"};
        HSSFRow row = sheet.createRow(rowNum);
        for (int i =0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text =new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        if (workbook !=null) {
            try {
                String fileName ="学生名单模板" +".xls";
                //下载后的excel名称可以为中文
                String downloadFileName =new String(fileName.getBytes("UTF-8"),"iso-8859-1");
                String headStr ="attachment; filename=\"" + downloadFileName +"\"";
                response.setContentType("APPLICATION/OCTET-STREAM");
                response.setHeader("Content-Disposition", headStr);
                OutputStream out = response.getOutputStream();
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return RestResponse.ok("成功");
    }

    private List<DownloadData> data() {
        List<DownloadData> list = new ArrayList<DownloadData>();
        for (int i = 0; i < 10; i++) {
            DownloadData data = new DownloadData();
            data.setString("字符串" + 0);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }

    @RequestMapping(value = "downloadEasyExcel",method = RequestMethod.GET)
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
    }**/
}
